import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:xvideos/hj_model/user/wallet_model_entity.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/home_business/widget/publist_entry_alert.dart';
import 'package:xvideos/hj_page/mine_business/make_money/mine_withdrawal_record_page.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/indicator/custom_tab_indicator.dart';

import '../make_money/withdrawal_page.dart';
import 'mine_publish_logic.dart';
import 'mine_publish_sub_logic.dart';
import 'mine_publish_sub_page.dart';

///我发布的帖子
class MinePublishPostPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MinePublishPostPageState();
  }
}

class _MinePublishPostPageState extends State<MinePublishPostPage> with TickerProviderStateMixin {
  final tabs = ['已发布', '待审核', '未通过'];
  WalletModelEntity? get wallet => globalStore.getWallet();
  late final tabCtr = TabController(length: tabs.length, vsync: this);

  bool inEdit = false;

  @override
  void initState() { 
    super.initState();
    tabCtr.addListener(_onTabChanged);
  }

  @override
  void dispose() {
    tabCtr.removeListener(_onTabChanged);
    tabCtr.dispose();
    super.dispose();
  }

  void _onTabChanged() {
    setState(() {});
  }

  void _setSelectedTabDatas() {
    final logic = Get.find<MinePublishLogic>();
    if (tabCtr.index == 2) {
      logic.dataSource = List<VideoModel>.from(Get.find<MinePublishSubLogic>(tag: '2').dataSource);
    } else {
      logic.dataSource = [];
    } 
    logic.update();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: MinePublishLogic(),
      builder: (controller) {
        return Scaffold(
            appBar: AppBar(
              title: Text("创作中心", style: textStyle(18, Color(0xE5FFFFFF), FontWeight.w600)),
              actions: [
                Visibility(
                  visible: tabCtr.index == 2,
                  child: TextButton(
                    onPressed: () {
                      if (inEdit) {
                        controller.clearChecked();
                      }
                      else{
                        _setSelectedTabDatas();
                      }
                      setState(() => inEdit = !inEdit);
                    },
                    child: Text(
                      inEdit ? '完成' : '编辑',
                      style: TextStyle(
                        color: Color(0xFF989898),
                        fontSize: 12,
                      ),
                    ),
                  ),
                )
              ],
            ),
            body: Stack(
              children: [
                Column(
                  children: [
                    Consumer<GlobalStore>(
                      builder: (context, store, child) {
                        return Container(
                          margin: EdgeInsets.symmetric(horizontal: 16, vertical: 18),
                          padding: EdgeInsets.fromLTRB(0, 14, 0, 22),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(8)),
                            color: Colors.white.withOpacity(.05),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                children: [
                                  _buildItem(
                                    '收益余额',
                                    '${wallet?.income}',
                                    '立即提现',
                                    () => Get.to(WithdrawalPage()),
                                  ),
                                  _buildItem(
                                    '累计收益',
                                    '${wallet?.vidIncome}',
                                    '业绩明细',
                                    () => Get.to(RecordsPage(RecordType.income)),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                    _buildTabbar(),
                    Expanded(child: _buildContent())
                  ],
                ),
                if (!inEdit)
                  Positioned(
                    right: 20,
                    bottom: 50,
                    child: PublishButton(
                      entry: PublishEntry.community,
                    ),
                  ),
                if (inEdit)
                  Positioned(
                    left: 0,
                    right: 0,
                    height: 62,
                    bottom: MediaQuery.of(context).viewInsets.bottom,
                    child: Container(
                      margin: EdgeInsets.symmetric(horizontal: 20),
                      decoration: BoxDecoration(
                        color: Color(0xFF303030),
                        borderRadius: BorderRadius.circular(3),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          GestureDetector(
                            onTap: () {
                              controller.selectAllOrNot();
                            },
                            child: Container(
                              width: 112,
                              height: 24,
                              alignment: Alignment.center,
                              child: Text(
                                controller.isAllChecked ? '取消全选' : '全选',
                                style: TextStyle(color: Color(0x99FFFFFF), fontSize: 16),
                              ),
                            ),
                          ),
                          Container(
                            width: 1,
                            height: 20,
                            color: Color(0x1AFFFFFF),
                          ),
                          GestureDetector(
                            onTap: controller.isEmptyChecked ? null: () {
                              controller.delete();
                            },
                            child: Container(
                              width: 112,
                              height: 38,
                              decoration: BoxDecoration(
                                color: Color(0xFFF52C56).withOpacity(controller.isEmptyChecked ? 0.5 : 1),
                                borderRadius: BorderRadius.circular(3),
                              ),
                              alignment: Alignment.center,
                              child: Text(
                                '删除(${controller.checkedList.length})',
                                style: TextStyle(color: Colors.white.withOpacity(controller.isEmptyChecked ? 0.5 : 1), fontSize: 16),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
              ],
            ));
      },
    );
  }

  _buildTabbar() {
    return TabBar(
      padding: const EdgeInsets.only(left: 12),
      tabAlignment: TabAlignment.fill,
      controller: tabCtr,
      onTap: (index) {
        if (index != 2 && inEdit) {
          // 如果切换到非"未通过"标签页，强制退出编辑模式
          setState(() {
            inEdit = false;
            Get.find<MinePublishLogic>().clearChecked();
          });
        }
      },
      tabs: List.generate(
          tabs.length,
          (index) => Padding(
                padding: const EdgeInsets.only(top: 12, bottom: 4),
                child: FittedBox(
                  child: Text(tabs[index]),
                ),
              )),
      isScrollable: false,
      labelColor: Colors.white.withOpacity(.9),
      labelStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
      unselectedLabelColor: Colors.white.withOpacity(0.35),
      unselectedLabelStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w400),
      indicator: CustomIndicator(
        width: 13,
        height: 3,
        topLeft: 2,
        topRight: 2,
        bottomLeft: 2,
        bottomRight: 2,
        useGradient: true,
        gradientColors: [
          Color(0xffE1351F).withOpacity(0),
          Color(0xffE1351F),
        ],
      ),
    );
  }

  _buildItem(String title, String count, String actionTitle, Function() action) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          title,
          style: TextStyle(color: Colors.white.withOpacity(.7), fontWeight: FontWeight.w500, fontSize: 14),
        ),
        6.sizeBoxH,
        Text(
          count,
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500, fontSize: 24),
        ),
        6.sizeBoxH,
        GestureDetector(
          onTap: () => action.call(),
          child: Container(
            width: 72,
            height: 25,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(13.5)),
              color: Color(0xffE1351F),
            ),
            child: Text(
              actionTitle,
              style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w500, fontSize: 12.0),
            ),
          ),
        ),
      ],
    );
  }

  _buildContent() {
    return Expanded(
      child: TabBarView(
        controller: tabCtr,
        physics: inEdit && tabCtr.index == 2 ? const NeverScrollableScrollPhysics() : null,
        children: [
          MinePublishSubPage(status: 1, inEdit: false),
          MinePublishSubPage(status: 0, inEdit: false),
          MinePublishSubPage(status: 2, inEdit: inEdit),
        ],
      ),
    );
  }
}
